import { useUserStore } from '@/stores'
import auth from '@/utils/auth'
import { ElMessage } from 'element-plus'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
    },
    {
      path: '/',
      name: 'layout',
      component: () => import('@/views/LayoutView.vue'),
      children: [
        { path: '', name: 'home', component: () => import('@/views/HomeVue.vue') },
        { path: 'article', name: 'article', component: () => import('@/views/ArticleView.vue') },
        { path: 'publish/:id?', name: 'publish', component: () => import('@/views/PublishView.vue') },
      ],
    },
  ],
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const token = auth.getToken()
  if (to.path !== '/login' && !token) {
    ElMessage.error('登录信息失效,请重新登录')
    const { setRedirectUrl } = useUserStore()
    setRedirectUrl(to.fullPath)
    next('/login')
  } else {
    next()
  }
})

export default router
